﻿namespace Leetcode.N1116;

using System.Threading;
public class ZeroEvenOdd
{
    private int n;
    private AutoResetEvent zeroResetEvent = new AutoResetEvent(true);
    private AutoResetEvent evenResetEvent = new AutoResetEvent(false);
    private AutoResetEvent oddResetEvent = new AutoResetEvent(false);

    public ZeroEvenOdd(int n)
    {
        this.n = n;
    }

    public void Zero(Action<int> printNumber)
    {

        for (int i = 0; i < this.n; i++)
        {
            this.zeroResetEvent.WaitOne();

            printNumber(0);
            if (i % 2 == 0)
            {
                this.evenResetEvent.Set();
            }
            else
            {
                this.oddResetEvent.Set();
            }
        }

    }

    public void Even(Action<int> printNumber)
    {


        for (int i = 2; i <= n; i += 2)
        {
            this.oddResetEvent.WaitOne();
            printNumber(i);
            this.zeroResetEvent.Set();
        }
    }

    public void Odd(Action<int> printNumber)
    {
        for (int i = 1; i <= n; i += 2)
        {
            this.evenResetEvent.WaitOne();
            printNumber(i);
            this.zeroResetEvent.Set();
        }
    }
}